package work.xiaohong.arithmetic.IO;

import lombok.Cleanup;
import work.xiaohong.arithmetic.entity.User;

import java.io.*;

/**
 * @author xiaohong
 * @version 1.0
 * @date 2021/10/27 0027 13:06
 * @description 字符流
 */
public class ReaderAndWriter {

    public static void main(String[] args) throws Exception {
//        writeFile();
//        readFile();
        copyFile();
    }

    // 写入字符
    public static void writeFile() throws Exception {
        @Cleanup
        FileWriter fileWriter = new FileWriter("a.txt");

        fileWriter.write("好好学习");

    }


    // 读取字符
    public static void readFile() throws Exception {
        @Cleanup
        FileReader fileReader = new FileReader("a.txt");

        char[] buffer = new char[2];
        int data = 0;
        // fileReader.read返回的是读取到的字符个数，到尾部了就返回-1
        while ((data = fileReader.read(buffer)) != -1){
            System.out.println(new String(buffer,0,data));
        }

    }


    // 复制文件
    public static void copyFile() throws Exception {
        @Cleanup
        FileReader fileReader = new FileReader("a.txt");
        @Cleanup
        FileWriter fileWriter = new FileWriter("b.txt",true);

        char[] buffer = new char[2];
        int data = 0;
        // fileReader.read返回的是读取到的字符个数，到尾部了就返回-1
        while ((data = fileReader.read(buffer)) != -1){
            fileWriter.write(new String(buffer,0,data));
        }

    }

}
